<?php
header("Content-Type: application/json; charset=utf-8");
session_start();

// 数据库配置（与宝塔一致）
$dbConfig = [
    'host' => 'localhost',
    'user' => 'itops_help1_center',
    'pass' => 'itops_help1_center',
    'name' => 'itops_help1_center',
    'charset' => 'utf8mb4'
];

// 连接数据库
try {
    $pdo = new PDO(
        "mysql:host={$dbConfig['host']};dbname={$dbConfig['name']};charset={$dbConfig['charset']}",
        $dbConfig['user'],
        $dbConfig['pass']
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'msg' => '服务器连接失败，请稍后重试']);
    exit;
}

// 接收参数
$username = trim($_POST['username'] ?? '');
$password = trim($_POST['password'] ?? '');

// 验证空值
if (empty($username) || empty($password)) {
    echo json_encode(['status' => 'error', 'msg' => '用户名和密码不能为空']);
    exit;
}

// 查询用户（表名改为users，密码字段改为user_pwd）
try {
    // 表名：users，密码字段：user_pwd，与实际表结构匹配
    $stmt = $pdo->prepare("SELECT id, username, user_pwd FROM users WHERE username = ? LIMIT 1");
    $stmt->execute([$username]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    // 验证用户是否存在
    if (!$user) {
        echo json_encode(['status' => 'error', 'msg' => '用户名不存在']);
        exit;
    }

    // 验证密码（使用user_pwd字段，假设密码用md5加密）
    if (md5($password) != $user['user_pwd']) {
        echo json_encode(['status' => 'error', 'msg' => '密码错误']);
        exit;
    }

    // 登录成功：记录Session
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    echo json_encode(['status' => 'success', 'msg' => '登录成功，正在跳转...']);
    exit;

} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'msg' => '登录异常，请稍后重试']);
    exit;
}